package com.bigflexlib.x.mx.controls.Accordion
{
	import flash.events.MouseEvent;
	
	import mx.containers.Accordion;
	import mx.controls.Button;
	import mx.core.UIComponent;
	
	public class AccordionHoverChangeHelper
	{
		

		private var acc:Accordion;
		
		
		public function AccordionHoverChangeHelper( acc:Accordion )
		{
			
			this.acc = acc;
			
			init( );
		}
		
		
		private function init( ):void
		{
			acc.addEventListener( MouseEvent.MOUSE_OVER, acc_mouseHover );
			acc.addEventListener( MouseEvent.MOUSE_DOWN, acc_mouseDown, true, 0xcccccc, true );
		}




		/**
		 * 
		 * These tests were defined through introspection of the current impl. ( flex 3 ) and the docs.
		 * 
		 * @param target
		 * @return 
		 * 
		 */
		private function isAccordionHeader( target:Object ):Boolean
		{
			
			var uic:Button = target as Button;			// docs say it must be a subclass of button
			
			if ( uic == null )
				return false;
			
			if ( ! acc.rawChildren.contains( uic ) )	// headers are rawChildren of accordion
				return false;
			
			
			if ( acc.getChildIndex( uic ) <= acc.numChildren )	// but must not be within visible children ( invisible children are off bounds )
				return false;
			

			return true;
		
		}
		
	

		/**
		 * 
		 * Determines if the passed object is a header and returns its index ( zero based )
		 * otherwise returns -1
		 * 
		 * @param target
		 * @return 
		 * 
		 */		
		private function getHeaderIndex( target:Object ):int
		{
			if ( ! isAccordionHeader( target ) )
				return -1;
				
			var name:String = ( target as UIComponent ).name;
			
			if ( name.indexOf("_header") == -1 )
				return -1;
				
			return int( Number( name.substr( 7 ) ) );
		}
		
		


		private function acc_mouseHover( event:MouseEvent ):void
		{
			
			var index:int = getHeaderIndex( event.target );
			
			if ( index == -1 )
				return;
				
			if ( acc.selectedIndex == index )
				return;
				
			acc.selectedIndex = index;
			
		}
		

		private function acc_mouseDown( event:MouseEvent ):void
		{
			if ( !isAccordionHeader( event.target ) )
				return;
			event.preventDefault( );			
		}		




	}
	
	
	
	
}














